'''
The Perl language.
'''

import re

from . import _base, _lang

NAME = "Perl"

class PerlEnvironment(_base.Environment):
    
    # I am currently uninterested in exposing the Perl interpreter's 
    # command-line arguments.
    has_arguments = False
    
    def __init__(self, host, path, version):
        self.language = _lang.Perl
        self.host = host
        self.path = path
        self.version = version
                
def check_using_exec(host, path, environment_list):
    pl = host.popen([path, '--version'])
    stdoutdata, stderrdata = pl.communicate()
    all_data = stdoutdata + stderrdata
    m = re.search(r'This is perl.*\bv([0-9.]+).* built for (\S+)', all_data)
    if m:
        version, build = m.groups()
        if 'cygwin' in build:
            description = 'Perl (Cygwin)'
        elif 'ActiveState' in all_data:
            description = 'ActiveState Perl'
        elif 'strawberry' in path.lower():
            # HACK: Currently the best way I know of to detect Strawberry Perl.
            description = 'Strawberry Perl'
        else:
            description = 'Perl'
        environment_list[_lang.Perl.name][description].append(
            PerlEnvironment(host, path, '%s (%s)' % (version, build)))

def check_using_full_path(host, path, environment_list):
    if host.path_exists(path):
        check_using_exec(host, path, environment_list)

def check_using_which(host, path, environment_list):
    """
    Checks $PATH for Perl executables by calling which(1), and adds any found
    to environment_list.
    """
    which = host.popen(['which', path])
    which.wait()
    if which.returncode == 0:
        check_using_exec(host, path, environment_list)

def configure(host_list, environment_list):
    """
    Configures this language by checking each host in host_list and adding
    detected environments to environment_list.  (Same for all auto-loading
    configure methods.)
    """
    for host in host_list:
        if 'nt' in host.os_name_list:
            check_using_full_path(host, r'c:\Perl\bin\perl.exe', environment_list)
            check_using_full_path(host, r'c:\Perl64\bin\perl.exe', environment_list)
            check_using_full_path(host, r'c:\cygwin\bin\perl.exe', environment_list)
            check_using_full_path(host, r'c:\strawberry\perl\bin\perl.exe', environment_list)
        else:
            check_using_which(host, 'perl', environment_list)
